package acs.bridge;

import acs.bridge.dao.BridgeDAOImpl;
import acs.bridge.dao.bm_load_fileImpl;
import acs.bridge.model.bm_file_model;
import acs.bridge.model.bm_load_ch_way4_model;
import acs.bridge.model.bm_load_way4_model;
import org.apache.log4j.Logger;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;


import java.io.File;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * acs.bridge
 * User: KuznetsovStV
 * Date: 24.06.13
 * Time: 11:27
 */
public class bm_load_way4 implements BridgeModuleInterface, BridgeModuleExtInterface {
    static String version = "4";
    Logger logger = Logger.getLogger(this.getClass().getName());

    private BridgeDAOImpl bridgeDAOImpl;

    private acs.bridge.dao.bm_load_way4DAOImpl bm_load_way4DAOImpl;
    private String tempFilePath;
    private String deleteTempFile;

    private String check_contract_number = "1";

    public String getReloadFile() {
        return reloadFile;
    }

    public void setReloadFile(String reloadFile) {
        this.reloadFile = reloadFile;
    }

    private String reloadFile;
    private String copyFile;

    public bm_load_fileImpl getBm_load_fileImpl() {
        return bm_load_fileImpl;
    }

    public void setBm_load_fileImpl(bm_load_fileImpl bm_load_fileImpl) {
        this.bm_load_fileImpl = bm_load_fileImpl;
    }

    private acs.bridge.dao.bm_load_fileImpl bm_load_fileImpl;

    public bm_load_file_interface getLoad_file_interface() {
        return load_file_interface;
    }

    public void setLoad_file_interface(bm_load_file_interface load_file_interface) {
        this.load_file_interface = load_file_interface;
    }

    private bm_load_file_interface load_file_interface;

    public String getRaw_table_postfix() {
        return raw_table_postfix;
    }

    public void setRaw_table_postfix(String raw_table_postfix) {
        this.raw_table_postfix = raw_table_postfix;
    }

    private String raw_table_postfix;

    public String getCh_handler() {
        return ch_handler;
    }

    public void setCh_handler(String ch_handler) {
        this.ch_handler = ch_handler;
    }

    private String ch_handler = "0";

    @Override
    public void execute(String a_group_tag, String a_meta_tag, BigDecimal a_raw_id, String a_module_tag) throws BridgeModuleException {
        logger.info("bm_load_way4 " + this.getClass().getName() + " ver." + version + " {raw_id=" + a_raw_id + "}");

        String l_filename = null;
        File tempFile = null;
        try {

               /* получить название файла */
            l_filename = bridgeDAOImpl.get_string_field_by_id(a_group_tag, a_meta_tag, a_raw_id, "FILE_NAME", "RAW");

                /* получить размер файла */
            String l_filesize = bridgeDAOImpl.get_string_field_by_id(a_group_tag, a_meta_tag, a_raw_id, "FILE_SIZE", "RAW");

            logger.info("filename=" + l_filename);

           /* Копируем файл во временный каталог */
            if (copyFile.equals("1")) {
                /* Проверяем наличие файла в каталоге */
                tempFile = new File(tempFilePath + l_filename);
                if (!tempFile.exists() || getReloadFile().equals("1")) {
                    logger.info("Reload file");
                    if (tempFile.exists())
                        tempFile.delete();
                    load_file_interface.get_file(l_filename, tempFilePath);
                }

            }

            if (tempFile == null) {
                if (tempFile.exists()) {
                    long l_size_before = Long.getLong(l_filesize);
                    long l_size_after = tempFile.length();
                    if (l_size_before != l_size_after) {
                        throw new BridgeModuleException("File size error {filename=" + l_filename + ",size_before=" + l_size_before + ",size_after=" + l_size_after + "}");
                    }
                }
            }


            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser saxParser = factory.newSAXParser();

            if (ch_handler.equals("1")) {
                bm_load_way4DAOImpl.deleteTmpFile_ch();
                bm_load_ch_way4_handler l_bm_load_ch_way4_handler = new bm_load_ch_way4_handler();
                l_bm_load_ch_way4_handler.setCheck_contract_number(getCheck_contract_number());
                l_bm_load_ch_way4_handler.setBm_load_way4DAOImpl(bm_load_way4DAOImpl);
                AtomicReference<DefaultHandler> handler = new AtomicReference<DefaultHandler>(l_bm_load_ch_way4_handler);
                saxParser.parse(tempFilePath + l_filename, handler.get());
                logger.info("count=" + l_bm_load_ch_way4_handler.g_count);
            } else {
                bm_load_way4DAOImpl.deleteTmpFile();
                bm_load_way4_handler l_bm_load_way4_handler = new bm_load_way4_handler();
                l_bm_load_way4_handler.setCheck_contract_number(getCheck_contract_number());
                l_bm_load_way4_handler.setBm_load_way4DAOImpl(bm_load_way4DAOImpl);
                AtomicReference<DefaultHandler> handler = new AtomicReference<DefaultHandler>(l_bm_load_way4_handler);
                saxParser.parse(tempFilePath + l_filename, handler.get());
                logger.info("count=" + l_bm_load_way4_handler.g_count);
            }

            bm_load_way4DAOImpl.getJdbcTemplate().getDataSource().getConnection().commit();

        } catch (Exception e) {
            throw new BridgeModuleException(e.getMessage());

        } finally {
            if (getDeleteTempFile().equals("1")) {
                if (l_filename != null) {
                    File file = new File(tempFilePath + l_filename);
                    file.delete();
                    logger.info(tempFilePath + l_filename + " deleted.");

                }
            }
        }
    }


    public void execute_meta_start(String a_group_tag, String a_meta_tag) {
        logger.info("execute_meta_start");

        String l_table_name = bridgeDAOImpl.fnc_schema_by_group(a_group_tag, a_meta_tag) + "." + "FBI_RAW_" + a_meta_tag;

        if (raw_table_postfix != null)
            l_table_name = l_table_name + raw_table_postfix;

        List<bm_file_model> l_bm_file_model_list = load_file_interface.get_directory_list();

        bm_file_model l_bm_file_model = null;
        Iterator l_bm_file_model_itr = l_bm_file_model_list.iterator();

        while (l_bm_file_model_itr.hasNext()) {
            l_bm_file_model = (bm_file_model) l_bm_file_model_itr.next();


            if (bridgeDAOImpl.fnc_get_fr_id_exists(l_bm_file_model.getFr_id(), a_group_tag, a_meta_tag) == 0) {

                bm_load_fileImpl.insertRawFile(l_table_name, l_bm_file_model.getFr_id(), l_bm_file_model.getFile_name(), l_bm_file_model.getFile_path(), l_bm_file_model.getLast_modified(), l_bm_file_model.getFile_size());
                logger.info("File '" + l_bm_file_model.getFr_id() + "' processed.");
            }

        }

        try {
            bm_load_fileImpl.getJdbcTemplate().getDataSource().getConnection().commit();
        } catch (SQLException e) {
            logger.error(e.getMessage());
        }

    }

    public void execute_meta_finish(String a_group_tag, String a_meta_tag) {
        logger.info("execute_meta_finish");
    }


    public void setBridgeDAOImpl(BridgeDAOImpl bridgeDAOImpl) {
        this.bridgeDAOImpl = bridgeDAOImpl;
    }

    public BridgeDAOImpl getBridgeDAOImpl() {
        return bridgeDAOImpl;
    }


    public static void main(String[] args) {

    }

    public void setBm_load_way4DAOImpl(acs.bridge.dao.bm_load_way4DAOImpl bm_load_way4DAOImpl) {
        this.bm_load_way4DAOImpl = bm_load_way4DAOImpl;
    }

    public acs.bridge.dao.bm_load_way4DAOImpl getBm_load_way4DAOImpl() {
        return bm_load_way4DAOImpl;
    }

    public void setTempFilePath(String tempFilePath) {
        this.tempFilePath = tempFilePath;
    }

    public String getTempFilePath() {
        return tempFilePath;
    }

    public void setDeleteTempFile(String deleteTempFile) {
        this.deleteTempFile = deleteTempFile;
    }

    public String getDeleteTempFile() {
        return deleteTempFile;
    }

    public void setCopyFile(String copyFile) {
        this.copyFile = copyFile;
    }

    public String getCopyFile() {
        return copyFile;
    }


    /* Запускается перед запуском интерфейса */
    public void initial_processing() {

    }

    /* Запускается после обработки интерфейса */
    public void final_processing(BigDecimal taskID) {
        logger.info("Final processing started. {fbu_wm.final_unv_file}");
        bm_load_way4DAOImpl.final_processing(taskID);
        logger.info("Final processing finished.");
    }

    public String getCheck_contract_number() {
        return check_contract_number;
    }

    public void setCheck_contract_number(String check_contract_number) {
        this.check_contract_number = check_contract_number;
    }
}
